<template>
  <a-drawer width="35%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <k-form-build
        :value="formJson"
        :dynamicData="dictData"
        ref="formBuild" />
    <div class="bottom-control">
      <a-space>
        <a-button type="primary" @click="submitForm">
          保存
        </a-button>
        <a-button type="dashed" @click="cancel">
          取消
        </a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>

import { addData, updateData, getData } from '@/api/free/data'

export default {
  name: 'CreateForm',
  props: {
    tableName: {
      type: String,
      required: true
    },
    dictData: {
      type: Object
    },
    formJson: {
      type: Object
    }
  },
  components: {
  },
  data () {
    return {
      loading: false,
      formTitle: '',
      open: false,
      id: ''
    }
  },
  filters: {
  },
  created () {
  },
  computed: {
    
  },
  watch: {
  },
  methods: {
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.id = ''
      this.$refs.formBuild.reset()
    },
     /** 新增按钮操作 */
    handleAdd () {
      this.open = true
      this.formTitle = '添加数据'
    },
    /** 修改按钮操作 */
    handleUpdate (id) {
      this.open = true
      this.id = id
      getData(this.tableName, id).then(response => {
        this.$refs.formBuild.setData(response)
        this.formTitle = '修改数据'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.formBuild.getData().then(res => {
        if (this.id) {
          res.id = this.id
          updateData(this.tableName, res).then(response => {
            this.$message.success(
              '修改成功',
              3
            )
            this.reset()
            this.open = false
            this.$emit('ok')
          })
        } else {
          addData(this.tableName, res).then(response => {
            this.$message.success(
              '新增成功',
              3
            )
            this.reset()
            this.open = false
            this.$emit('ok')
          })
        }
      }).catch(e => {
        console.error('获取数据失败', e)
      })
    }
  }
}
</script>
